/**
 * Class: DMesh
 *
 * Purpose: 
 *
 * Created: Feb 19, 2010 @ 11:50:50 AM
 * @author Ken Scott
 */
package org.openfantasia.util.math.geometry;

import org.openfantasia.util.math.DPoint3;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class DMesh {

	protected DPoint3 position = new DPoint3();

	protected List<DVertex> vertices = new ArrayList<DVertex>();

	protected Map<String, DVertex> vertexMap = new TreeMap<String, DVertex>();

	protected List<DPolygon> polygons = new ArrayList<DPolygon>();


	public DMesh() {
	}


	public DMesh(List<DVertex> vertices) {
		this.vertices = vertices;
	}


	public void addVertex(DVertex vertex) {
		if (!vertices.contains(vertex)) {
			polygons.clear();
			vertices.add(vertex);
			vertexMap.put(vertex.getId(), vertex);
			vertex.setParent(this);
		}
	}


	public void removeVertex(DVertex vertex) {
		if (vertices.remove(vertex)) {
			polygons.clear();
			vertexMap.remove(vertex.getId());
			vertex.setParent(null);
		}
	}


	public DVertex getVertex(String id) {
		return vertexMap.get(id);
	}


	public List<DVertex> getVertices() {
		return vertices;
	}


	public List<DPolygon> getPolygons() {
		if ((polygons == null) || polygons.isEmpty()) {
			polygons = new ArrayList<DPolygon>();
			for (DVertex vertex : vertices) {
				List<DPolygon> nPolys = vertex.getPolygons();
				for (DPolygon p : nPolys) {
					if (!polygons.contains(p)) {
						polygons.add(p);
					}
				}
			}
		}
		return polygons;
	}
}